package com.framework.modules.live.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.framework.common.config.SystemConfigName;
import com.framework.common.live.TencentLiveKit;
import com.framework.common.utils.DateUtils;
import com.framework.common.utils.QuickHelper;
import com.framework.common.validator.ValidatorUtils;
import netscape.javascript.JSObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.framework.modules.live.entity.LiveRoomEntity;
import com.framework.modules.live.service.LiveRoomService;
import com.framework.common.utils.PageUtils;
import com.framework.common.utils.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;


/**
 * 直播室信息 
 *
 * @author MIT
 * @email litmiss@gmail.com
 * @date 2020-11-04 14:35:52
 */
@RestController
@RequestMapping("live/liveroom")
@Api(tags = "LiveRoomController")
public class LiveRoomController {
    @Autowired
    private LiveRoomService liveRoomService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("live:liveroom:list")
    @ApiOperation("list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = liveRoomService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{uid}")
    @RequiresPermissions("live:liveroom:info")
    @ApiOperation("info")
    public R info(@PathVariable("uid") Integer uid) {
        LiveRoomEntity liveRoom = liveRoomService.selectById(uid);

        return R.ok().put("liveRoom", liveRoom);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("live:liveroom:save")
    @ApiOperation("save")
    public R save(@RequestBody LiveRoomEntity liveRoom) {
        liveRoomService.insert(liveRoom);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("live:liveroom:update")
    @ApiOperation("update")
    public R update(@RequestBody LiveRoomEntity liveRoom) {
        ValidatorUtils.validateEntity(liveRoom);
        liveRoomService.updateAllColumnById(liveRoom);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("live:liveroom:delete")
    @ApiOperation("delete")
    public R delete(@RequestBody Integer[] uids) {
        liveRoomService.deleteBatchIds(Arrays.asList(uids));

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/set_room_state")
    @RequiresPermissions("live:liveroom:update")
    @ApiOperation("设置直播室状态")
    public R set_room_state(@RequestParam(value = "uid", defaultValue = "0") Integer uid, @RequestParam(value = "state", defaultValue = "0") Integer state,@RequestParam(value = "remark", defaultValue = "") String remark) {

        if (uid <= 0) {
            return R.error("对不起，用户编号参数设置错误");
        }

        //腾讯云直播配置
        JSONObject sdkConfig = QuickHelper.getConfigValue("sys.zhibo.sdk.config", JSONObject.class);

        JSONObject activeTemplate = sdkConfig.getJSONObject("templateConfig").getJSONObject(sdkConfig.getString("active"));
        String secretId = sdkConfig.getString("secretId");
        String secretKey = sdkConfig.getString("secretKey");
        String domainName = activeTemplate.getString("PushDomain");
        String appName = "live";

        //查询当前直播室直播状态
        LiveRoomEntity entity = liveRoomService.selectById(uid);
        if (entity == null) {
            return R.error("对不起，没有找到该直播室");
        }

        //如果当前正在直播
        if (state == -2) {

            Boolean result = TencentLiveKit.forbidLiveStreamRequest(uid.toString(), domainName, appName, secretId, secretKey);
            String msg = "1.禁止直播成功<br />";
            if (result) {
                LiveRoomEntity entity2 = new LiveRoomEntity();
                entity2.setUid(uid);
                entity2.setState(state);
                entity2.setForbiddenMsg(remark);
                entity2.setForbiddenEndTime(QuickHelper.getNowTimeStampSeconds());
                Boolean result2 = liveRoomService.updateById(entity2);
                if (result2) {
                    return R.ok();
                } else {
                    return R.error("变更直播室状态错误，请联系管理员");
                }
            } else {
                return R.error("断播失败，云直播SDK调用失败");
            }
        } else {

            /**
             * 如果是恢复直播，则调用腾讯SDK恢复直播接口
             */
            if(entity.getState() == -2){
                TencentLiveKit.resumeLiveStream(uid.toString(), domainName, appName, secretId, secretKey);
            }
            LiveRoomEntity entity2 = new LiveRoomEntity();
            entity2.setUid(uid);
            entity2.setState(state);
            entity2.setForbiddenMsg("");
            entity2.setForbiddenEndTime(0);
            Boolean result = liveRoomService.updateById(entity2);
            return result ? R.ok().put("sdkconfig", sdkConfig) : R.error("变更直播室状态错误，请联系管理员");
        }
    }

    @RequestMapping("/get_live_play_url")
    @RequiresPermissions("live:liveroom:list")
    @ApiOperation("设置直播室状态")
    public R get_live_play_url(String uid){
        JSONObject obj = QuickHelper.getConfigJSONObject(SystemConfigName.ZHIBO_SDK_CONFIG);
        String active = obj.getString("active");
        JSONObject activeConfig = obj.getJSONObject("templateConfig").getJSONObject(active);

        //推流密钥
        String apikey = activeConfig.getString("ApiKey");

        //播放域名
        String playDomain = activeConfig.getString("PlayDomain");
        Integer expiredSeconds = DateUtils.getSecondTimestamp(new Date()) + 10 * 60 * 1000;
        Map<String, String> map = new HashMap<>();
        map.put("FLV", String.format("http://%s/live/%s.flv", playDomain, uid));
        map.put("RTMP", String.format("rtmp://%s/live/%s", playDomain, uid));
        map.put("HLS", String.format("http://%s/live/%s.m3u8", playDomain, uid));
        map.put("UDP", String.format(String.format("webrtc://%s/live/%s", playDomain, uid)));
        return R.ok(map);
    }
}